﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Entity;
using System.Web;
using System.Web.Mvc;
using Site3AI.Models;
using M3AI.Services;

namespace M3AI.Controllers
{
    [Authorize]
    public class HomeController : _SiteBaseController
    {
        static Lazy<WeiXinService.Services.WxServices> _svc = new Lazy<WeiXinService.Services.WxServices>();
        WeiXinService.Services.WxServices WxService
        {
            get
            {
                return _svc.Value;
            }
        }
        void SetUserSetting(Guid userid,string[] keys,string[] vals) {
            var sts = DB.UserSettings.Where(v => v.UserID == userid).ToList();
            for (int i = 0; i < keys.Length; i++)
			{
                var us = sts.FirstOrDefault(v => v.SettingName == keys[i]);
                if (null == us) {
                    us = new UserSetting() { UserID=userid,ID=DB.NewID(), SettingName=keys[i] };
                    DB.UserSettings.Add(us);
                }
                us.SettingValue = vals[i];
                us.UpdateTime = DateTime.Now;
			}
            DB.SaveChanges();
        }
        public ActionResult BoundWeixin(string wxid) {

            try
            {
                var u = WxService.GetUerInfo(wxid);
                SetUserSetting(SiteUser.UserId,
                    new string[] { "wx.nickname", "wx.openid", "wx.headImg","wx.userinfo","wx.addr" },
                    new string[] {u.Result.nickname, u.Result.openid, u.Result.headimgurl, u.Raw.Result,
                        string.Format("{0} {1} {2}",  u.Result.country,u.Result.province,u.Result.city)});
                
            }
            catch(Exception ex) { 
                Console.WriteLine(ex.Message);
            }
            return RedirectToAction("Index");
        }
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Me()
        {
            return View(SiteUser);
        }

        [HttpPost]
        public ActionResult Me(aspnet_Users model)
        {
            return RedirectToAction("MeEdit");
        }

        public ActionResult MyEnhosp()
        {
            return View(SiteUser.UserAllRecupers);
        }


        public ActionResult MeEdit()
        {
            return View(SiteUser);
        }

        [HttpPost]

        public ActionResult MeEdit(aspnet_Users model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    //DB.aspnet_Users.Attach(model);
                    //DB.Entry<aspnet_Users>(model).State = System.Data.Entity.EntityState.Modified;
                    aspnet_Users user = DB.aspnet_Users.SingleOrDefault(u => u.UserId == model.UserId);
                    user.UserName = model.UserName;
                    user.MobileAlias = model.MobileAlias;
                    user.MobileAliasB = model.MobileAliasB;
                    user.HomePhone = model.HomePhone;
                    user.HomePhoneB = model.HomePhoneB;
                    user.OtherPhone = model.OtherPhone;
                    user.OtherPhoneB = model.OtherPhoneB;
                    user.Gender = model.Gender;
                    user.BirthDay = model.BirthDay;
                    user.UserHeight = model.UserHeight;
                    user.UserWeight = model.UserWeight;
                    user.SheBaoHao = model.SheBaoHao;
                    user.IDCodeType = model.IDCodeType;
                    user.IDCode = model.IDCode;
                    user.HuanZheLaiYuan = model.HuanZheLaiYuan;
                    user.Address = model.Address;
                    user.PostCode = model.PostCode;
                    user.Email = model.Email;
                    if (DB.SaveChanges() > 0)
                    {
                        ViewBag.SiteUser = model;
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        ModelState.AddModelError("", "修改个人信息失败，请检查内容是否正确！");
                    }
                }
                catch
                {
                    ModelState.AddModelError("", "修改个人信息失败，请检查内容是否正确！");
                }
            }
            return View(model);
        }

        public ActionResult KB()
        {
            //var uhs=SiteUser.UserAllRecupers.Select(v=>v.Hospital).Distinct();
            //var m = DB.CmsCatalogs.Where(v=> v.Hospitals.Intersect(uhs).Count()>0);
            var m = DB.CmsCatalogs;//
            return View(m);
        }
        public ActionResult KBCata(string id)
        {
            var m = DB.CmsCatalogs.Find(id);
            //TODO:check m.hospitals insect with siteuser's recuper's hospital
            return View(m);
        }
        public ActionResult KBItem(string id)
        {
            var m = DB.CmsItems.Find(id);
            return View(m);
        }
        public ActionResult MySF()
        {

            var u = SiteUser;
            var uid = u.UserId;
            var m = DB.QizSubjectObjForDoctors.Where(v => v.Recuper.GuoQi == false && v.Recuper.UserID == uid).Select(v => v.QizSubject).Distinct();
            ViewBag.Hospitals = DB.QizSubjectObjForDoctors.Where(v => v.Recuper.GuoQi == false && v.Recuper.UserID == uid && v.QizSubject != null).Select(v => v.QizSubject).Distinct().Select(s => s.Hospital.HospName).Distinct().ToList();

            return View(m);
        }
        [HttpGet]
        public ActionResult QizSessionEdit(string SubjectID, string ID, string RefAttID)
        {
            var TokenID = Now.Ticks.ToString();
            ViewBag.TokenID = TokenID;
            Session["Fix_QizSessionEdit_Token_" + TokenID] = "Yes";
            var m = Services.QizSessionEditInner_Get(SubjectID, ID, RefAttID);
            return ViewOrPartial(m);
        }

        [HttpPost]
        public ActionResult QizSessionEdit(QizSession tm, string TokenID, string RecuperID = "")
        {
            if (Session["Fix_QizSessionEdit_Token_" + TokenID] != null)
            {
                Session.Remove("Fix_QizSessionEdit_Token_" + TokenID);
                //var m = Services.QizSessionEditInner_Post(tm, RecuperID);
                Tuple<QizSession, bool> m = null;
                try
                {
                    m = Services.QizSessionEditInner_Post(tm, RecuperID);
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                {
                    var s = ex.ToString();
                    s += "\r\n\r\n==================================\r\n\r\n";
                    foreach (var item in ex.EntityValidationErrors)
                    {
                        s += "\r\n\r\n====ITEM=========================\r\n\r\n";
                        foreach (var ves in item.ValidationErrors)
                        {
                            s += ves.PropertyName + "=" + "[" + item.Entry.CurrentValues[ves.PropertyName] + "]::" + ves.ErrorMessage + "\r\n";

                        }
                    }
                    return Content("<pre>" + s + "</pre>");
                }
                Session["Fix_QizSessionEdit_TempSid"] = m.Item1.ID;
                if (m.Item2)
                {
                    return RedirectToAction("QizSessionEdit", new { PreviewOnly = true, ID = m.Item1.ID });
                }
                else
                {
                    ViewBag.TokenID = TokenID;
                    Session["Fix_QizSessionEdit_Token_" + TokenID] = "Yes";
                    return View(m.Item1);
                }
            }
            else
            {
                if (null != Session["Fix_QizSessionEdit_TempSid"])
                {
                    return RedirectToAction("QizSessionEdit", new { PreviewOnly = true, ID = (string)Session["Fix_QizSessionEdit_TempSid"] });
                }
                else
                {
                    throw new SiteException("如果网络速度较慢，可能会耗时较长，请耐心等待，勿重复的提交。");
                }
            }
        }

        [HttpGet]
        public ActionResult Img(string id, bool Preview = false)
        {
            if (!string.IsNullOrEmpty(id))
            {
                var idl = id.ToLower();
                var idext = System.IO.Path.GetExtension(idl);
                string[] exts = { ".png", ".jpg", ".gif", ".jpeg" };

                string fn = null;
                //string fnori = Server.MapPath("~/App_Data/FileDB/" + id);
                string fnOri = "/FileDB/" + id;
                fn = fnOri;

                bool isimg = exts.Contains(idext);
                if (!isimg)
                {
                    return File(GetFileData(id), "application/x-download");
                }
                else
                {
                    if (Preview)
                    {
                        fn = fnOri + ".thumb" + idext;
                        byte[] filedata = null;
                        try
                        {
                            filedata = GetFileData(fn);
                            if (null == filedata || filedata.Length == 0) throw new Exception("Not data");
                        }
                        catch
                        {

                            try
                            {
                                filedata = GetFileData(fnOri);
                                if (null == filedata || filedata.Length == 0) throw new Exception("Not data");
                                System.Web.Helpers.WebImage wi = new System.Web.Helpers.WebImage(filedata);
                                if (wi.Width > 300 || wi.Height > 300) wi.Resize(300, 300, true, true);
                                PutFileData(fn, wi.GetBytes());
                            }
                            catch
                            {
                            }

                            //rebuild previewimg


                        }

                    }
                    return File(GetFileData(fn), "image");
                }
            }
            else
            {
                return Content("No image");
            }
        }
        byte[] GetFileData(string fn)
        {
            StorageLib.IStorageProvider sp = StorageLib.StorageFactory.GetDefaultStorageProvider();
            try
            {
                return sp.GetData(fn);
            }
            catch (Exception ex)
            {
                MvcApplication.Log(ex.Message + "@RecuperController.GetFileData(fn=" + fn);
                return new byte[] { };
            }
        }
        void PutFileData(string fn, byte[] data)
        {
            StorageLib.StorageFactory.GetDefaultStorageProvider().PutData(fn, data);
        }
        /// <summary>
        /// 随访历史
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult Hist(string Source)
        {
            Dictionary<QizSubject, IEnumerable<QizSession>> model = new Dictionary<QizSubject, IEnumerable<QizSession>>();
            var subjects = DB.QizSessions.Where(v => v.UserID == SiteUser.UserId).Select(v => v.QizSubject).Distinct(); // SiteUser.UserAllRecupers.SelectMany(v => v.QizSubjectObjForDoctors).Select(v => v.QizSubject);
            if (subjects != null)
            {
                subjects = subjects.Where(s => s != null);
                if (Source == "指标库")
                {
                    subjects = subjects.Where(s => s.SubjectType == "指标库");
                }
                else
                {
                    subjects = subjects.Where(s => s.SubjectType != "指标库");
                }
                foreach (var subject in subjects)
                {
                    model[subject] = DB.QizSessions.Where(qs => qs.UserID == SiteUser.UserId && qs.QizSubjectID == subject.ID)
                        .OrderByDescending(v => v.CreationTime).ThenBy(v => v.QizSubjectID);
                }
            }

            return View(model);
        }

        [Authorize]
        public ActionResult QizSessionDeviant(string id, string back)
        {
            QizSession model = DB.QizSessions.Include(qs => qs.QizSubject).Include(qs => qs.QizSessionDetails)
                .SingleOrDefault(qs => qs.ID == id);
            ViewBag.Back = back;
            return View(model);
        }

        public ActionResult MemoList()
        {
            var m = new ListViewModel<CommonSearchValues, IQueryable<UserMemo>>()
            {
                PageIdx = 1,
                PageSize = M3AI.Services.Services.MobilePageSize,//M3AI.Services.Services.DefaultPageSize * 4,
                SearchFrom = new CommonSearchValues(),
                SearchTo = new CommonSearchValues()
            };
            var d = DB.UserMemoes.Where(v => v.UserID == SiteUser.UserId);
            m.ItemCount = d.Count();
            m.PageCount = (int)Math.Ceiling((double)d.Count() / m.PageSize);
            d = d.OrderByDescending(v => v.CreateTime).Skip((m.PageIdx - 1) * m.PageSize).Take(m.PageSize);
            m.Data = d;
            return View(m);
        }

        [HttpPost]
        public ActionResult MemoList(ListViewModel<CommonSearchValues, IQueryable<UserMemo>> m)
        {
            if (null == m)
            {
                m = new ListViewModel<CommonSearchValues, IQueryable<UserMemo>>()
                {
                    PageIdx = 1,
                    PageSize = M3AI.Services.Services.MobilePageSize,//M3AI.Services.Services.DefaultPageSize * 4,
                    SearchFrom = new CommonSearchValues(),
                    SearchTo = new CommonSearchValues()
                };
            }
            var d = DB.UserMemoes.Where(v => v.UserID == SiteUser.UserId);
            if (m.SearchFrom != null)
            {
                if (!string.IsNullOrEmpty(m.SearchFrom.V1))
                {
                    var w = m.SearchFrom.V1.Trim();
                    d = d.Where(v => v.Title.Contains(w) || v.MemoText.Contains(w)
                        || (v.Recuper != null && (v.Recuper.Hospital.HospName.Contains(w)
                        || v.Recuper.Hospital.HospCode.Contains(w))));
                }
                if (!string.IsNullOrEmpty(m.SearchFrom.V2))
                {
                    var w = DateTime.Parse(m.SearchFrom.V2);
                    d = d.Where(v => v.CreateTime >= w);
                }
            }
            if (m.SearchTo != null)
            {
                if (!string.IsNullOrEmpty(m.SearchTo.V2))
                {
                    var w = DateTime.Parse(m.SearchTo.V2).AddDays(1);
                    d = d.Where(v => v.CreateTime <= w);
                }
            }
            m.ItemCount = d.Count();
            m.PageCount = (int)Math.Ceiling((double)m.ItemCount / m.PageSize);
            d = d.OrderByDescending(v => v.CreateTime).Skip((m.PageIdx - 1) * m.PageSize).Take(m.PageSize);
            m.Data = d;

            if (!Request.IsAjaxRequest())
            {
                return View(m);
            }
            else
            {
                return PartialView("MemoListPartial", m);
            }
        }
        [HttpGet]
        public ActionResult MemoEdit(string id)
        {
            Session["MemoEdit_Timestamp"] = Now;
            return View(string.IsNullOrEmpty(id) ? new UserMemo() { Timemark = MvcApplication.Now.Date } : DB.UserMemoes.FirstOrDefault(v => v.UserID == SiteUser.UserId && v.ID == id));
        }
        [HttpPost]
        public ActionResult MemoEdit(UserMemo m)
        {
            if (((DateTime)Session["MemoEdit_Timestamp"]).AddSeconds(10) > Now)
            {
                ViewBag.Resubmit = true;
                return View(m);
            }
            var filefield = "memopicfile";
            var sir = Services.SaveRequestImage(filefield, m.MemoPic);
            var haserror = sir.Item1;
            m.MemoPic = sir.Item2;

            if (m.Timemark < Site3AI.Models.Site3AIEntities.ZeroTime) m.Timemark = Now;
            m.CreateTime = Now;

            if (string.IsNullOrEmpty(m.ID))
            {
                m.UserID = SiteUser.UserId;
                m.ID = DB.NewID();
                DB.UserMemoes.Add(m);
            }
            else
            {
                if (m.UserID != SiteUser.UserId) throw new SiteException("行为错误！");
                var om = DB.UserMemoes.FirstOrDefault(v => v.ID == m.ID && v.UserID == SiteUser.UserId);
                if (null == om) throw new SiteException("数据错误！");

                DB.Entry(om).CurrentValues.SetValues(m);
            }

            if (haserror)
            {
                ModelState.AddModelError("memopicfile", "图片有问题。");
            }
            else
            {
                try
                {
                    DB.SaveChanges();
                    Session["MemoEdit_Timestamp"] = Now;
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                {
                    var s = string.Empty;
                    foreach (var item in ex.EntityValidationErrors)
                    {
                        foreach (var ves in item.ValidationErrors)
                        {
                            s += ves.ErrorMessage + "\r\n"; //ves.PropertyName + "=" + "[" + item.Entry.CurrentValues[ves.PropertyName] + "]::" + ves.ErrorMessage + "\r\n";

                        }
                    }
                    ModelState.AddModelError("数据验证问题", "部分数据填写的有问题，请保存失败。");
                    return View(m);
                    //throw new SiteException("部分数据填写的有问题，请保存失败。");
                }
            }
            return RedirectToAction("MemoList", new { IsView = true });
        }
        [HttpGet]
        public ActionResult MemoEditJcd(string id)
        {
            return View(new UserMemo() { Title = "检查单照片附件", Timemark = MvcApplication.Now.Date });
        }
        [HttpPost]
        public ActionResult MemoEditJcd(UserMemo m, string KeyWord)
        {
            if (!string.IsNullOrEmpty(KeyWord)) m.Title = "[" + KeyWord + "]" + (string.IsNullOrEmpty(m.Title) ? "检查单照片附件" : m.Title.Trim());
            string mid = m.ID;

            if (m.Timemark < Site3AI.Models.Site3AIEntities.ZeroTime) m.Timemark = Now;
            m.CreateTime = Now;
            var haserror = false;
            if (string.IsNullOrEmpty(mid))
            {

                var hasfile = false;
                foreach (var filefield in Request.Files.AllKeys)
                {
                    if (Request.Files[filefield].ContentLength > 0)
                    {
                        hasfile = true;
                        var sir = Services.SaveRequestImage(filefield, m.MemoPic);
                        haserror = haserror || sir.Item1;
                        m.MemoPic = sir.Item2;

                        var nm = new UserMemo()
                        {
                            ID = DB.NewID(),
                            UserID = SiteUser.UserId,
                            Title = m.Title,
                            CreateTime = m.CreateTime,
                            MemoPic = sir.Item2,
                            MemoText = m.MemoText,
                            RecuperID = m.RecuperID,
                            Timemark = m.Timemark
                        };
                        nm.ID = DB.NewID();
                        DB.UserMemoes.Add(nm);
                    }
                }
                if (!hasfile)
                {
                    ModelState.AddModelError("nofile", "没有选择任何检查单，请至少选择一个照片。");
                    return View(m);
                }
            }


            if (haserror)
            {
                ModelState.AddModelError("memopic", "图片有问题。未能全部保存成功。");
            }
            else
            {
                try
                {
                    DB.SaveChanges();
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                {
                    var s = string.Empty;
                    foreach (var item in ex.EntityValidationErrors)
                    {
                        foreach (var ves in item.ValidationErrors)
                        {
                            s += ves.ErrorMessage + "\r\n";

                        }
                    }
                    ModelState.AddModelError("数据验证问题", "部分数据填写的有问题，请保存失败。");
                    return View(m);
                }
            }
            return RedirectToAction("MemoList", new { IsView = true });
        }

        public ActionResult Medic()
        {
            return View("Implemented");
        }

        public ActionResult Timeline()
        {
            return View("Implemented");
        }

        public ActionResult QizSmsSessionList()
        {
            var model = new ListViewModel<CommonSearchValues, IQueryable<QizSmsSession>>()
            {
                PageIdx = 1,
                PageSize = M3AI.Services.Services.MobilePageSize,
                SearchFrom = new CommonSearchValues(),
                SearchTo = new CommonSearchValues()
            };
            IQueryable<QizSmsSession> d = null;
            if (SiteUser.aspnet_Roles.Any(v => v.RoleName == "Enginner" || v.RoleName == "Admin"))
            {
                d = DB.QizSmsSessions.AsQueryable();
            }
            else if (SiteUser.aspnet_Roles.Any(v => v.RoleName == "Recuper"))
            {
                d = DB.QizSmsSessions.Where(v => v.Recuper.UserID == SiteUser.UserId);
            }
            d = d.Where(v => v.SessionStatus == 3);
            model.ItemCount = d.Count();
            model.PageCount = (int)Math.Ceiling((double)model.ItemCount / model.PageSize);
            d = d.OrderByDescending(v => v.CreationTime);
            model.Data = d.Skip(model.PageSize * (model.PageIdx - 1)).Take(model.PageSize);
            ViewBag.Subjects = SiteUser.UserAllRecupers.SelectMany(v => v.QizSubjectObjForDoctors).Select(v => v.QizSmsSubject);
            return View(model);
        }

        [HttpPost]
        public ActionResult QizSmsSessionList(ListViewModel<CommonSearchValues, IQueryable<QizSmsSession>> model)
        {
            if (null == model)
            {
                model = new ListViewModel<CommonSearchValues, IQueryable<QizSmsSession>>()
                {
                    PageIdx = 1,
                    PageSize = M3AI.Services.Services.MobilePageSize,
                    SearchFrom = new CommonSearchValues { V1 = string.Empty, V2 = string.Empty, V3 = string.Empty },
                    SearchTo = new CommonSearchValues { V3 = string.Empty }
                };
            }
            IQueryable<QizSmsSession> d = null;
            if (SiteUser.aspnet_Roles.Any(v => v.RoleName == "Enginner" || v.RoleName == "Admin"))
            {
                d = DB.QizSmsSessions.AsQueryable();
            }
            else if (SiteUser.aspnet_Roles.Any(v => v.RoleName == "Recuper"))
            {
                d = DB.QizSmsSessions.Where(v => v.Recuper.UserID == SiteUser.UserId);
            }
            d = d.Where(v => v.SessionStatus == 3);

            #region Search

            if (null != model.SearchFrom)
            {
                if (!string.IsNullOrWhiteSpace(model.SearchFrom.V1))
                {
                    d = d.Where(v => v.QizSmsSubjectMonthIdx.QizSmsSubjectID == model.SearchFrom.V1);
                }
                //if (!string.IsNullOrWhiteSpace(model.SearchFrom.V4))
                //{
                //    string v4 = model.SearchFrom.V4;
                //    var v4a = model.SearchFrom.V4.Split(':');

                //    if (v4a.Length > 1)
                //    {
                //        v4 = v4a[1];
                //        d = d.Where(v => v.QizSmsSubjectMonthIdx.QizSmsSubject.ID == v4);
                //    }
                //    else
                //    {
                //        d = d.Where(v => v.QizSmsSubjectMonthIdx.QizSmsSubjectID == v4
                //            || v.QizSmsSubjectMonthIdx.QizSmsSubject.Title.Contains(v4));
                //    }

                //}
                //if (!string.IsNullOrEmpty(model.SearchFrom.V2))
                //{
                //    var o = Guid.Empty;
                //    Guid.TryParse(model.SearchFrom.V2, out o);
                //    d = d.Where(v => v.UserID == o || v.User.UserName.Contains(model.SearchFrom.V2));
                //}
                if (!string.IsNullOrEmpty(model.SearchFrom.V3))
                {
                    var o = DateTime.Parse(model.SearchFrom.V3);
                    d = d.Where(v => v.Timemark >= o);
                }
                if (null != model.SearchTo)
                {
                    if (!string.IsNullOrEmpty(model.SearchTo.V3))
                    {
                        var o = DateTime.Parse(model.SearchTo.V3);
                        d = d.Where(v => v.Timemark <= o);
                    }
                }
            }

            #endregion

            model.ItemCount = d.Count();
            model.PageCount = (int)Math.Ceiling((double)model.ItemCount / model.PageSize);
            d = d.OrderByDescending(v => v.CreationTime);
            model.Data = d.Skip(model.PageSize * (model.PageIdx - 1)).Take(model.PageSize);
            ViewBag.Subjects = SiteUser.UserAllRecupers.SelectMany(v => v.QizSubjectObjForDoctors).Select(v => v.QizSmsSubject);
            return View(model);
        }

        public ActionResult QizSmsSessionView(string id)
        {
            QizSmsSession model = DB.QizSmsSessions.Where(v => v.ID == id).FirstOrDefault();
            if (model != null && model.UnRead)
            {
                model.UnRead = false;
                DB.SaveChanges();
            }
            return View(model);
        }

        public ActionResult GetQizSmsUnReadCount()
        {
            IQueryable<QizSmsSession> d = null;
            if (SiteUser.aspnet_Roles.Any(v => v.RoleName == "Enginner" || v.RoleName == "Admin"))
            {
                d = DB.QizSmsSessions.AsQueryable();
            }
            else if (SiteUser.aspnet_Roles.Any(v => v.RoleName == "Recuper"))
            {
                d = DB.QizSmsSessions.Where(v => v.Recuper.UserID == SiteUser.UserId);
            }
            int count = d.Count(v => v.SessionStatus == 3 && v.UnRead);
            return Content(count.ToString(), "text/html");
        }

        public ActionResult MyQizCommList()
        {
            var model = new ListViewModel<CommonSearchValues, IQueryable<CommonSearchValues2<DateTime, string, string>>>
            {
                PageIdx = 1,
                PageSize = M3AI.Services.Services.MobilePageSize,
                SearchFrom = new CommonSearchValues(),
                SearchTo = new CommonSearchValues()
            };
            var qn = from v in DB.SmsSents
                     join d in DB.aspnet_Users on v.SenderName equals d.UserName
                     where v.ReceiverName == SiteUser.UserName && v.SmsType == "医生留言"
                     orderby v.SentTime descending
                     select new CommonSearchValues2<DateTime, string, string>()
                     {
                         V1 = d.Hospital.HospName,
                         V2 = d.Department.DepName,
                         V3 = d.UserName,
                         V4 = v.TextMessage,
                         V11 = v.SentTime.Value,
                         V6 = v.ProcStatus,
                         V0 = d.BingQu.Title,
                     };
            model.ItemCount = qn.Count();
            model.PageCount = (int)Math.Ceiling((double)model.ItemCount / model.PageSize);
            qn = qn.OrderByDescending(v => v.V11);
            model.Data = qn.Skip(model.PageSize * (model.PageIdx - 1)).Take(model.PageSize);
            return View(model);
        }

        [HttpPost]
        public ActionResult MyQizCommList(ListViewModel<CommonSearchValues, IQueryable<CommonSearchValues2<DateTime, string, string>>> model)
        {
            if (null == model)
            {
                model = new ListViewModel<CommonSearchValues, IQueryable<CommonSearchValues2<DateTime, string, string>>>
                {
                    PageIdx = 1,
                    PageSize = M3AI.Services.Services.MobilePageSize,
                    SearchFrom = new CommonSearchValues(),
                    SearchTo = new CommonSearchValues()
                };
            }
            var qn = from v in DB.SmsSents
                     join d in DB.aspnet_Users on v.SenderName equals d.UserName
                     where v.ReceiverName == SiteUser.UserName && v.SmsType == "医生留言"
                     orderby v.SentTime descending
                     select new CommonSearchValues2<DateTime, string, string>()
                     {
                         V1 = d.Hospital.HospName,
                         V2 = d.Department.DepName,
                         V3 = d.UserName,
                         V4 = v.TextMessage,
                         V11 = v.SentTime.Value,
                         V6 = v.ProcStatus,
                         V0 = d.BingQu.Title,
                     };
            model.ItemCount = qn.Count();
            model.PageCount = (int)Math.Ceiling((double)model.ItemCount / model.PageSize);
            qn = qn.OrderByDescending(v => v.V11);
            model.Data = qn.Skip(model.PageSize * (model.PageIdx - 1)).Take(model.PageSize);
            return View(model);
        }

        public ActionResult SysSmsSessionList()
        {
            var model = new ListViewModel<CommonSearchValues, IQueryable<SmsSent>>()
            {
                PageIdx = 1,
                PageSize = M3AI.Services.Services.MobilePageSize,
                SearchFrom = new CommonSearchValues(),
                SearchTo = new CommonSearchValues()
            };
            var d = DB.SmsSents.Where(v => v.ReceiverCode == SiteUser.MobileAlias && v.SmsType != "医生留言");
            model.ItemCount = d.Count();
            model.PageCount = (int)Math.Ceiling((double)model.ItemCount / model.PageSize);
            d = d.OrderByDescending(v => v.SentTime);
            model.Data = d.Skip(model.PageSize * (model.PageIdx - 1)).Take(model.PageSize);
            return View(model);
        }

        [HttpPost]
        public ActionResult SysSmsSessionList(ListViewModel<CommonSearchValues, IQueryable<SmsSent>> model)
        {
            if (null == model)
            {
                model = new ListViewModel<CommonSearchValues, IQueryable<SmsSent>>()
                {
                    PageIdx = 1,
                    PageSize = M3AI.Services.Services.MobilePageSize,
                    SearchFrom = new CommonSearchValues(),
                    SearchTo = new CommonSearchValues()
                };
            }
            var d = DB.SmsSents.Where(v => v.ReceiverCode == SiteUser.MobileAlias && v.SmsType != "医生留言");

            if (null != model.SearchFrom)
            {
                if (!string.IsNullOrEmpty(model.SearchFrom.V1))
                {
                    var w = DateTime.Parse(model.SearchFrom.V1);
                    d = d.Where(v => v.SentTime >= w);
                }
            }
            model.ItemCount = d.Count();
            model.PageCount = (int)Math.Ceiling((double)model.ItemCount / model.PageSize);
            d = d.OrderByDescending(v => v.SentTime);
            model.Data = d.Skip(model.PageSize * (model.PageIdx - 1)).Take(model.PageSize);
            return View(model);
        }
    }
}
